package com.onesports.intelligent.k12.polarlight.common.utils;

import com.onesports.framework.kit.common.util.TimeUtils;
import com.onesports.intelligent.k12.polarlight.common.errors.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
import java.util.*;

/**
 * @author
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

//    public static void main(String[] args) {
//        System.out.println(DateUtils.dateTimeNowSSS());
//    }


    private static final String YEAR = "year";
    private static final String MONTH = "month";
    private static final String WEEK = "week";
    private static final String DAY = "day";

    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    public static String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
    public static String HH_MM = "HH:mm";
    public static String HH_MM_SS = "HH:mm:ss";

    /** yyyy-MM-dd */
    private static final DateTimeFormatter yyyyMMdd_EN = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNowSSS() {
        return dateTimeNow(YYYYMMDDHHMMSSSSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }


    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算相差天数 包含今天
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        String date1Str = DateUtils.dateTime(date1);
        String date2Str = DateUtils.dateTime(date2);
        Date newDate1;
        Date newDate2;
        try {
            newDate1 = DateUtils.parseDate(date1Str,DateUtils.YYYY_MM_DD);
            newDate2 =DateUtils.parseDate(date2Str,DateUtils.YYYY_MM_DD);
        } catch (ParseException e) {
            throw new BusinessException("日期格式化出错");
        }
        return Math.abs((int) ((newDate1.getTime() - newDate2.getTime()) / (1000 * 3600 * 24))) +1;
    }
    public static int differentMin(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        //long day = diff / nd;
        //// 计算差多少小时
        //long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff  / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return (int)min;
    }
    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static Date strToDate(String param){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(YYYYMMDDHHMMSS);
        LocalDateTime ldt = LocalDateTime.parse(param,dtf);
        return Date.from(ldt.atZone( ZoneId.systemDefault()).toInstant());
    }

    public static Calendar getCalendar(Date date, String format){
        if(date == null){
            date = new Date();
        }

        Calendar calender = Calendar.getInstance();
        calender.setTime(date);

        return calender;
    }

    /**
     * 增加分钟
     * @param minute
     * @param date
     * @param format
     * @return
     */
    public static Date addMinuteToDate(int minute,Date date,String format) {
        Calendar calendar = getCalendar(date, format);


        calendar.add(Calendar.MINUTE, minute);

        return calendar.getTime();
    }

    /**
     * 根据日期计算星期
     *
     * @param dateTime 日期时间
     * @return {@link String}
     */
    public static String dateToWeek(Date dateTime){
        String[] weekDays = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        //指示一个星期中的某天
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if(w < 0){
            w = 0;
        }
        return  weekDays[w];
    }


    /**
     * 根据日期计算星期
     *
     * @param dateTime 日期时间
     * @return {@link String}
     */
    public static String dateToWeekCode(Date dateTime){
        String[] weekDays = {"7","1","2","3","4","5","6"};
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        //指示一个星期中的某天
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if(w < 0){
            w = 0;
        }
        return  weekDays[w];
    }

    /**
     * Date转LocalDate
     * @param date
     */
    public static LocalDate date2LocalDate(Date date) {
        if(null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * 计算当前日期与{@code endDate}的间隔天数
     *
     * @param endDate
     * @return 间隔天数
     */
    public static long localDateCompare(LocalDate endDate){
        return LocalDate.now().until(endDate, ChronoUnit.DAYS);
    }

    /**
     *  计算N天后的日期
     *
     * @param num 天
     * @return {@link String}
     */
    public static String getAfterTimePlus(LocalDate localDate, Long num) {
        return localDate.plusDays(num).format(yyyyMMdd_EN);
    }


    /**
     * 获取两个日期之间的所有日期
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return List<Date>
     */
    public static List<Date> allDaysBetweenTwoDate(Date startDate, Date endDate) {
        List<Date> listDate = new ArrayList<>();
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            while (calendar.getTime().before(endDate) || calendar.getTime().equals(endDate)) {
                listDate.add(calendar.getTime());
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            return listDate;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listDate;
    }

    /**
     * 判断当前时间是否在指定时间范围
     *
     * @param from 开始时间
     * @param to   结束时间
     * @return 结果
     */
    public static boolean between(LocalDate from, LocalDate to) {
        if (from == null) {
            throw new IllegalArgumentException("开始时间不能为空");
        }
        if (to == null) {
            throw new IllegalArgumentException("结束时间不能为空");
        }
        LocalDate now = LocalDate.now();
        return now.isAfter(from) && now.isBefore(to);
    }

    /**
     * 字符串转LocalDate
     *
     * @param strDate str日期
     * @param pattern 模式
     * @return {@link LocalDate}
     */
    public static LocalDate stringToLocalDate(String strDate, String pattern) {
        if (StringUtils.isBlank(strDate)){
            return null;
        }
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);
        return LocalDate.parse(strDate, fmt);
    }

    /**
     * 获取两个日期之间的所有日期
     *
     * @param startTime
     *            开始日期
     * @param endTime
     *            结束日期
     * @return
     */
    public static List<String> getDays(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            // 日期加1(包含结束)
            tempEnd.add(Calendar.DATE, +1);
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * Date转LocalDate
     *
     * @param date 日期
     * @return {@link LocalDate}
     */
    public static LocalDate dateToLocalDate(Date date) {
        if(null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * 获取当前日期和时间字符串.
     *
     * @return String 日期时间字符串，例如 2015-08-11 09:51
     */
    public static String getLocalDateTimeStr() {
        return format(LocalDateTime.now(), YYYY_MM_DD_HH_MM);
    }

    /**
     * 获取日期时间字符串
     *
     * @param temporal 需要转化的日期时间
     * @param pattern  时间格式
     * @return String 日期时间字符串，例如 2015-08-11 09:51
     */
    public static String format(TemporalAccessor temporal, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(temporal);
    }

    /**
     * 日期时间字符串转换为日期时间(java.time.LocalDateTime)
     *
     * @param localDateTimeStr 日期时间字符串
     * @param pattern          日期时间格式 例如DATETIME_PATTERN
     * @return LocalDateTime 日期时间
     */
    public static LocalDateTime parseLocalDateTime(String localDateTimeStr, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(localDateTimeStr, dateTimeFormatter);
    }

    public static boolean between(LocalDate now, LocalDate from, LocalDate to) {
        if (from == null) {
            throw new IllegalArgumentException("开始时间不能为空");
        }
        if (to == null) {
            throw new IllegalArgumentException("结束时间不能为空");
        }
        return now.isAfter(from) && now.isBefore(to);
    }

    /**
     * date转localDateTime
     *
     * @param date
     * @return
     */
    public static LocalDateTime date2LocalDateTime(Date date) {
        if (date == null) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }



    public static void main(String[] args) {
        System.out.println(getDays("2018-06-28", "2018-07-3"));
        System.out.println(getLocalDateTimeStr());
        Date date = new Date();
        int minute = 180;
        Date ultimateDate = DateUtils.addMinuteToDate(minute, date, DateUtils.YYYY_MM_DD_HH_MM);
        System.out.println("计算后的时间:"+ TimeUtils.toText(ultimateDate,DateUtils.YYYY_MM_DD_HH_MM));
        String nowDate = getLocalDateTimeStr();
        System.out.println("当前时间:"+nowDate);

    }

}
